#include <QHeaderView>
#include <QInputDialog>
#include <QDesktopServices>
#include <QDebug>
#include <QUrl>
#include <QItemDelegate>
#include <QItemEditorCreatorBase>
#include <QStandardItemEditorCreator>

#include "parameterswindow.h"
#include "ui_parameterswindow.h"
#include "../database/databasemanager.h"
#include "countrycombobox.h"

namespace Jcr
{

class ParametersWindowPrivate
{
public:
    ParametersWindowPrivate();
    ~ParametersWindowPrivate();

    void populateParamLabels();
    void readModelParams(const QString& model);
    void writeModelParamsToSqlite(const QString& model);
    void writeModelParamsToMysql(const QString& model);

    QString model;
    QStringList paramLabels;
    Ui::ParametersWindow* ui;
};

ParametersWindowPrivate::ParametersWindowPrivate()
{
    ui = new Ui::ParametersWindow;
}

ParametersWindowPrivate::~ParametersWindowPrivate()
{
    delete ui;
}

/// new version of paramters
// release_date
// emission_volume
// manufacture_state
// cylinder_count
// length_width_height
// travel
// shaft_distance
// cooling_style
// seat_height
// compression_ratio
// break_style
// max_capacity
// land_distance
// max_torsion
// empty_weight
// gas_supply_style
// full_weight
// economical_gas_cost
// max_speed
// env_protection_standard
// wheel_count
// ignition_style
// wheel_type
// clutch_type
// front_wheel_standard
// transmission_type
// back_wheel_standard
// colors
// gas_volume
// country
// cn_yuan
// us_dollars
// eu_euros
// type {standard, custom, cruiser, dirt bike, scooter, dual sport, sportbike, touring, super moto}

void ParametersWindowPrivate::populateParamLabels()
{
    paramLabels = QStringList() << QObject::tr("Release Data") << QObject::tr("Emission Volume") << QObject::tr("Manufacture State")
                                << QObject::tr("Cylinder Count") << QObject::tr("Length-Width-Height") << QObject::tr("Travel") << QObject::tr("Shaft Distance")
                                << QObject::tr("Cooling Style") << QObject::tr("Seat Height") << QObject::tr("Compression Ratio") << QObject::tr("Break Style")
                                << QObject::tr("Max Capacity") << QObject::tr("Land Distance") << QObject::tr("Max Torsion") << QObject::tr("Empty Weight")
                                << QObject::tr("Gas Supply Style") << QObject::tr("Full Weight") << QObject::tr("Economical Gas Cost") << QObject::tr("Max Speed")
                                << QObject::tr("Env Protection Standard") << QObject::tr("Wheel Count") << QObject::tr("Ignition Style") << QObject::tr("Wheel Type")
                                << QObject::tr("Clutch Type") << QObject::tr("Front Wheel Standard") << QObject::tr("Transmission Type") << QObject::tr("Back Wheel Standard")
                                << QObject::tr("Colors") << QObject::tr("Gas Volume") << QObject::tr("Country") << QObject::tr("CN_Yuan") << QObject::tr("US_Dollars")
                                << QObject::tr("EU_Euros") << QObject::tr("Type");
    ui->paramsTable->setColumnCount(2);
    ui->paramsTable->setHorizontalHeaderLabels(QStringList() << QObject::tr("Name") << QObject::tr("Value"));
    ui->paramsTable->setRowCount(paramLabels.size());

    for (int i = 0; i < paramLabels.size(); ++i) {
        QTableWidgetItem* item = new QTableWidgetItem;
        item->setText(paramLabels.at(i));
        item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
        ui->paramsTable->setItem(i, 0, item);
    }
}

void ParametersWindowPrivate::readModelParams(const QString& model)
{
    if (model.isEmpty())
        return;

    QStringList params = Jcr::DatabaseManager::instance()->modelParams(model);
    if (params.isEmpty())
        return;

    for (int i = 0; i < params.size(); ++i) {
        QTableWidgetItem* item = new QTableWidgetItem;
        item->setText(params.at(i));
        ui->paramsTable->setItem(i, 1, item);

        if (i == 29)
            item->setData(Qt::DisplayRole, params.at(i));
    }
    ui->paramsTable->resizeColumnsToContents();

    QStringList videoLinks = Jcr::DatabaseManager::instance()->modelVideoLinks(model);
    ui->videoLinkList->clear();

    //
    ui->tabWidget->tabBar()->setTabTextColor(2, videoLinks.isEmpty() ? Qt::red : Qt::black);
    foreach (auto link, videoLinks) {
        QListWidgetItem* item = new QListWidgetItem;
        item->setCheckState(Qt::Unchecked);
        item->setText(link);
        ui->videoLinkList->addItem(item);
    }

    QStringList newsLinks = Jcr::DatabaseManager::instance()->modelNewsLinks(model);
    ui->newsLinkList->clear();
    ui->tabWidget->tabBar()->setTabTextColor(1, newsLinks.isEmpty() ? Qt::red : Qt::black);
    foreach (auto link, newsLinks) {
        QListWidgetItem* item = new QListWidgetItem;
        item->setCheckState(Qt::Unchecked);
        item->setText(link);
        ui->newsLinkList->addItem(item);
    }
}

void ParametersWindowPrivate::writeModelParamsToSqlite(const QString& model)
{
    if (model.isEmpty())
        return;

}

void ParametersWindowPrivate::writeModelParamsToMysql(const QString& model)
{
    if (model.isEmpty())
        return;

}

ParametersWindow::ParametersWindow(QWidget *parent) : QWidget(parent)
{
    setMinimumWidth(300);
    d_ptr = new ParametersWindowPrivate;
    d_ptr->ui->setupUi(this);

    d_ptr->ui->videoLinkList->setAlternatingRowColors(true);
    d_ptr->ui->paramsTable->setAlternatingRowColors(true);
    d_ptr->ui->tabWidget->setCurrentIndex(0);
    d_ptr->populateParamLabels();
    d_ptr->ui->paramsTable->resizeColumnsToContents();

    setWindowTitle(QObject::tr("Model Parameters"));

//    QItemEditorFactory *factory = new QItemEditorFactory;

//    QItemEditorCreatorBase *countryListCreator =
//        new QStandardItemEditorCreator<Jcr::CountryComboBox>();

//    factory->registerEditor(QVariant::String, countryListCreator);

//    QItemEditorFactory::setDefaultFactory(factory);

    connect(d_ptr->ui->addVideoButton, SIGNAL(clicked()), this, SLOT(addVideoLink()));
    connect(d_ptr->ui->deleteVideoButton, SIGNAL(clicked()), this, SLOT(deleteVideoLink()));
    connect(d_ptr->ui->updateSQLiteButton, SIGNAL(clicked()), this, SLOT(updateToSqlite()));
    connect(d_ptr->ui->videoLinkList, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(onDblClickedListItem(QListWidgetItem*)));
}

ParametersWindow::~ParametersWindow()
{
    delete d_ptr;
}

void ParametersWindow::setModel(const QString &model)
{
    if (d_ptr->model != model) {
        d_ptr->model = model;

        d_ptr->ui->modelLabel->setText(model);
        d_ptr->ui->brandLabel->setText(Jcr::DatabaseManager::instance()->brandName(model));
        d_ptr->readModelParams(model);
    }
}

QString ParametersWindow::model() const
{
    return d_ptr->model;
}

void ParametersWindow::updateToSqlite()
{
    QStringList params;
    for (int i = 0; i < d_ptr->ui->paramsTable->rowCount(); ++i) {
        QTableWidgetItem* paramItem = d_ptr->ui->paramsTable->item(i, 1);
        params.append(paramItem->text());
    }
    Jcr::DatabaseManager::instance()->updateModelParams(d_ptr->model, params);
}

void ParametersWindow::updateToMysql()
{

}

void ParametersWindow::addVideoLink()
{
    QString link = QInputDialog::getText(this, tr("Add Video Link"), tr("Url:"));
    if (link.isEmpty())
        return;

    QListWidgetItem* item = new QListWidgetItem;
    item->setText(link);
    item->setCheckState(Qt::Unchecked);
    d_ptr->ui->videoLinkList->addItem(item);

    bool ok = Jcr::DatabaseManager::instance()->addModelVideoLink(d_ptr->model, link);
    if (ok)
        emit notify(tr("Add video link \"%1\" to \"%2\" successfully!").arg(link).arg(d_ptr->model));
    else
        emit notify(tr("Failed to add video link to model \"%1\"").arg(d_ptr->model));
}

void ParametersWindow::deleteVideoLink()
{
    Jcr::DatabaseManager* dbMgr = Jcr::DatabaseManager::instance();
    for (int i = 0; i < d_ptr->ui->videoLinkList->count(); ++i) {
        QListWidgetItem* item = d_ptr->ui->videoLinkList->item(i);
        if (item->checkState() == Qt::Checked)
            dbMgr->removeModelVideoLink(item->text());
    }
}

void ParametersWindow::onDblClickedListItem(QListWidgetItem* item)
{
    const QString url = item->text();
    QDesktopServices::openUrl(QUrl(url));
    qDebug() << url;
}

} // namespace jcr
